import sympy

# 直接创建矩阵
m1 = sympy.Matrix([[1, 2, 1], [1, 2, 3], [0, 1, 2]])
sympy.pprint(m1)
# 在矩阵基础上添加行
m2 = sympy.Matrix([m1, [2, 2, 2]])
sympy.pprint(m2)
# 给定行数列数创建矩阵
m3 = sympy.Matrix(2, 3, [1, 2, 3, 4, 5, 6])
sympy.pprint(m3)
# 通过函数创建矩阵
# 注意lambda表达式
f = lambda i, j: 1 if i == j else 0
m4 = sympy.Matrix(4, 4, f)
sympy.pprint(m4)
f2 = lambda i, j: i + j
m5 = sympy.Matrix(3, 3, f2)
sympy.pprint(m5)
# 单位矩阵
m6 = sympy.eye(3)
sympy.pprint(m6)
# 全0和全1矩阵
m7 = sympy.zeros(3)
m8 = sympy.ones(3)
sympy.pprint(m7)
sympy.pprint(m8)
# 对角矩阵
m17 = sympy.diag([1, 2, 3])
sympy.pprint(m17)
# 嵌套矩阵的对角矩阵
m18 = sympy.diag(-1, sympy.ones(2, 2), sympy.Matrix([3, 5, 5]))
sympy.pprint(m18)

# 修改矩阵元素
# 表示第三行第三列
m8[2, 2] = 2
sympy.pprint(m8)
# 表示第三个元素
m8[2] = 3
sympy.pprint(m8)
# 子矩阵 1:3表示从第二行（列）开始
m10 = m8[1:3, 1:3]
sympy.pprint(m10)
# 删除行和列
m8.row_del(1)
m8.col_del(1)
sympy.pprint(m8)

# 矩阵的运算
m11 = sympy.Matrix([[1, 2, 3], [3, 2, 1], [2, 2, 2]])
m12 = sympy.Matrix([[0, 1, 2], [1, 0, 1], [2, 1, 4]])
# 基本四则运算
sympy.pprint(m11 + m12)
sympy.pprint(m11 - m12)
sympy.pprint(m11 * m12)
sympy.pprint(m11 ** 2)
m13 = sympy.Matrix([1, 2, 1])
m14 = sympy.Matrix([1, 0, 3])
# 点乘(数量积)和叉乘(向量积)
sympy.pprint(m13.dot(m14))
sympy.pprint(m13.cross(m14))
sympy.pprint(m8)
# 求行列式
sympy.pprint(m8.det())
# 求拟矩阵 非方程以及奇异矩阵似乎没办法求，只能用scipy.linalg
sympy.pprint(m8.inv())
m15 = sympy.Matrix([[4, -2, 1], [-5, 6, 0], [7, 0, 3]])
m16 = sympy.Matrix([[1, 2, 3], [2, 3, 4]])
from scipy import linalg

a = [[4, -2, 1], [-5, 6, 0], [7, 0, 3]]
b = [[1, 2, 3], [2, 3, 4]]
print(linalg.pinv(a))
print(linalg.pinv(b))
